package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.AppointmentVo;
import com.antdesignbackend.backend.entity.entityVo.ChargingFlowVo;
import com.antdesignbackend.backend.service.ChargingFlowService;
import com.antdesignbackend.backend.service.IAppointmentService;
import com.antdesignbackend.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/chargingFlow")
public class ChargingFlowController {

    ReturnVO result = new ReturnVO();
    private Integer userId;
    private String roleID;
    private Integer menuId;

    @Autowired
    IAppointmentService appointmentService;
    @Autowired
    ChargingFlowService chargingFlowService;
    @Autowired
    UserService userService;
    @Autowired
    UserController userController;

    /**
     * 合伙人报表
     */
    @GetMapping("/partnerReport")
    @AuthToken
    public String partnerReport(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "flowManagement/partnerReport";
    }
    /**
     * 服务商报表
     */
    @GetMapping("/providerReport")
    @AuthToken
    public String providerReport(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "flowManagement/providerReport";
    }
    /**
     * 商铺报表
     */
    @GetMapping("/shopsReport")
    @AuthToken
    public String shopsReport(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "flowManagement/shopsReport";
    }
    /**
     * 会员报表
     */
    @GetMapping("/memberReport")
    @AuthToken
    public String memberReport(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "flowManagement/memberReport";
    }
    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody AppointmentVo data, HttpServletRequest request) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<AppointmentVo> datalist=new ArrayList<>();
        QueryWrapper<AppointmentVo> wrapper =new QueryWrapper<AppointmentVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //根据权限生成过滤条件
        if(roleID.equals("1")) {//管理员
        }else{//商户
            List<Integer> idList= userController.idList(userId);
            wrapper.in("userID",idList);
        }
        //正常查询过滤条件
        wrapper.eq("state",1);
        if(data.getStartTimeStr()!=null && !data.getStartTimeStr().equals("")){
            wrapper.ge("createTime",data.getStartTimeStr());
        }
        if(data.getEndTimeStr()!=null && !data.getEndTimeStr().equals("")){
            wrapper.le("createTime",data.getEndTimeStr());
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=chargingFlowService.countm(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= chargingFlowService.searchm(wrapper.orderByDesc("createTime"),new Page<>(data.getPageIndex(),data.getPageSize()));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 详细子表查询
     * @return
     */
    @PostMapping("/charglist")
    @ResponseBody
    @AuthToken
    public ReturnVO charglist(@RequestBody AppointmentVo data, HttpServletRequest request){
        result = new ReturnVO();
        List<ChargingFlowVo> datalist=new ArrayList<>();
        QueryWrapper<ChargingFlowVo> wrapper =new QueryWrapper<ChargingFlowVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //正常查询过滤条件
        wrapper.eq("c.attributionOrder",data.getOrderNumber());
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=chargingFlowService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= chargingFlowService.search(wrapper,new Page<>(data.getPageIndex(),data.getPageSize()));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 合伙人报表
     * @return
     */
    @PostMapping("/partnerlist")
    @ResponseBody
    @AuthToken
    public ReturnVO partnerlist(@RequestBody AppointmentVo data, HttpServletRequest request){
        result = new ReturnVO();
        List<ChargingFlowVo> datalist=new ArrayList<>();
        QueryWrapper<ChargingFlowVo> wrapper =new QueryWrapper<ChargingFlowVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //根据权限生成过滤条件
        if(roleID.equals("1")) {//管理员
        }else{//商户
            List<Integer> idList= userController.idList(userId);
            wrapper.in("u.userID",idList);
        }
        //正常查询过滤条件
        wrapper.eq("u.userType","2");
        if(data.getShopName()!=null && !data.getShopName().equals("")){
            wrapper.and(wra -> wra.like("c.name", data.getShopName()));
        }
        if(data.getStartTimeStr()!=null && !data.getStartTimeStr().equals("")){
            wrapper.ge("c.createTime",data.getStartTimeStr());
        }
        if(data.getEndTimeStr()!=null && !data.getEndTimeStr().equals("")){
            wrapper.le("c.createTime",data.getEndTimeStr());
        }
        ChargingFlowVo charg=chargingFlowService.totala(wrapper);
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=chargingFlowService.counta(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= chargingFlowService.searcha(wrapper,new Page<>(data.getPageIndex(),data.getPageSize()));
            datalist=dealList(datalist);
            datalist.forEach(model -> model.setTotalList(charg));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 服务商报表
     * @return
     */
    @PostMapping("/providerlist")
    @ResponseBody
    @AuthToken
    public ReturnVO providerlist(@RequestBody AppointmentVo data, HttpServletRequest request){
        result = new ReturnVO();
        List<ChargingFlowVo> datalist=new ArrayList<>();
        QueryWrapper<ChargingFlowVo> wrapper =new QueryWrapper<ChargingFlowVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //根据权限生成过滤条件
        if(roleID.equals("1")) {//管理员
        }else{//商户
            List<Integer> idList= userController.idList(userId);
            wrapper.in("u.userID",idList);
        }
        //正常查询过滤条件
        wrapper.eq("u.userType","3");
        if(data.getShopName()!=null && !data.getShopName().equals("")){
            wrapper.and(wra -> wra.like("c.name", data.getShopName()));
        }
        if(data.getStartTimeStr()!=null && !data.getStartTimeStr().equals("")){
            wrapper.ge("c.createTime",data.getStartTimeStr());
        }
        if(data.getEndTimeStr()!=null && !data.getEndTimeStr().equals("")){
            wrapper.le("c.createTime",data.getEndTimeStr());
        }
        ChargingFlowVo charg=chargingFlowService.totala(wrapper);
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=chargingFlowService.counta(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= chargingFlowService.searcha(wrapper,new Page<>(data.getPageIndex(),data.getPageSize()));
            datalist=dealList(datalist);
            datalist.forEach(model -> model.setTotalList(charg));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 商铺报表
     * @return
     */
    @PostMapping("/shopslist")
    @ResponseBody
    @AuthToken
    public ReturnVO shopslist(@RequestBody AppointmentVo data, HttpServletRequest request) throws ParseException {
        result = new ReturnVO();
        List<AppointmentVo> datalist=new ArrayList<>();
        QueryWrapper<AppointmentVo> wrapper =new QueryWrapper<AppointmentVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //根据权限生成过滤条件
        if(roleID.equals("1")) {//管理员
        }else{//商户
            List<Integer> idList= userController.idList(userId);
            wrapper.in("u.userID",idList);
        }
        //正常查询过滤条件
        //wrapper.eq("t3.merchantType","4");
        wrapper.eq("t.state","1");
        if(data.getShopName()!=null && !data.getShopName().equals("")){
            wrapper.and(wra -> wra.like("t3.name", data.getShopName()));
        }
        if(data.getStartTimeStr()!=null && !data.getStartTimeStr().equals("")){
            wrapper.ge("t.createTime",data.getStartTimeStr());
        }
        if(data.getEndTimeStr()!=null && !data.getEndTimeStr().equals("")){
            wrapper.le("t.createTime",data.getEndTimeStr());
        }
        AppointmentVo charg=appointmentService.total(wrapper);
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=appointmentService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= appointmentService.search(wrapper,new Page<>(data.getPageIndex(),data.getPageSize()));
            datalist=dealAppList(datalist);
            datalist.forEach(model -> model.setTotalList(charg));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 会员报表
     * @return
     */
    @PostMapping("/memberlist")
    @ResponseBody
    @AuthToken
    public ReturnVO memberlist(@RequestBody AppointmentVo data, HttpServletRequest request){
        result = new ReturnVO();
        List<ChargingFlowVo> datalist=new ArrayList<>();
        QueryWrapper<ChargingFlowVo> wrapper =new QueryWrapper<ChargingFlowVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //根据权限生成过滤条件
        if(roleID.equals("1")) {//管理员
        }else{//商户
            wrapper.inSql("u.userId","select userid from users where Activity=1 and UserID="+userId);
        }
        //正常查询过滤条件
        wrapper.eq("u.userType",5);
        if(data.getShopName()!=null && !data.getShopName().equals("")){
            wrapper.and(wra -> wra.like("c.name", data.getShopName()));
        }
        if(data.getStartTimeStr()!=null && !data.getStartTimeStr().equals("")){
            wrapper.ge("c.createTime",data.getStartTimeStr());
        }
        if(data.getEndTimeStr()!=null && !data.getEndTimeStr().equals("")){
            wrapper.le("c.createTime",data.getEndTimeStr());
        }
        ChargingFlowVo charg=chargingFlowService.totala(wrapper);
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=chargingFlowService.counta(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= chargingFlowService.searcha(wrapper,new Page<>(data.getPageIndex(),data.getPageSize()));
            datalist=dealList(datalist);
            datalist.forEach(model -> model.setTotalList(charg));
        }
        result.setData(datalist);
        return result;
    }

    public List<ChargingFlowVo> dealList(List<ChargingFlowVo> datalist){
        for(ChargingFlowVo charg:datalist){
            charg.setStatus(0);
            charg.setCreateTime(charg.getCreateTime().substring(0,charg.getCreateTime().indexOf(' ')));
        }
        for(int i=0;i<datalist.size();i++){
            ChargingFlowVo data=datalist.get(i);
            if (!data.getStatus().equals(1)) {
                Integer userId=data.getUserId();
                String date=data.getCreateTime();
                for (int j = i+1; j < datalist.size(); j++) {
                    if (!datalist.get(j).getStatus().equals(1)) {
                        ChargingFlowVo deal=datalist.get(j);
                        String time=deal.getCreateTime();
                        if (deal.getUserId().equals(userId) && date.equals(time)) {
                            data.setMoney(data.getMoney()+deal.getMoney());
                            data.setAmount(data.getAmount()+deal.getAmount());
                            data.setCreateTime(time);
                            deal.setStatus(1);
                        }
                    }
                }
                Iterator<ChargingFlowVo> iterator = datalist.iterator();
                while (iterator.hasNext()){
                    ChargingFlowVo chargingFlowVo= iterator.next();
                    if (chargingFlowVo.getStatus().equals(1)){
                        iterator.remove();
                    }
                }
            }
        }
        return datalist;
    }
    public List<AppointmentVo> dealAppList(List<AppointmentVo> datalist) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        for(AppointmentVo app:datalist){
            app.setStatus(0);
            String time=df.format(app.getCreateTime());
            app.setCreateTime(df.parse(time));
        }
        for(int i=0;i<datalist.size();i++){
            AppointmentVo data=datalist.get(i);
            if (!data.getStatus().equals(1)) {
                String shopName=data.getShopName();
                String date=df.format(data.getCreateTime());
                for (int j = i+1; j < datalist.size(); j++) {
                    if (!datalist.get(j).getStatus().equals(1)) {
                        AppointmentVo deal=datalist.get(j);
                        String time=df.format(deal.getCreateTime());
                        if (deal.getShopName().equals(shopName) && date.equals(time)) {
                            data.setAmount(data.getAmount()+deal.getAmount());
                            data.setCreateTime(deal.getCreateTime());
                            deal.setStatus(1);
                            datalist.remove(deal);
                        }
                    }
                }
                Iterator<AppointmentVo> iterator = datalist.iterator();
                while (iterator.hasNext()){
                    AppointmentVo appointmentVo= iterator.next();
                    if (appointmentVo.getStatus().equals(1)){
                        iterator.remove();
                    }
                }
            }
        }
        return datalist;
    }
    /***
     * 详细金额查询
     * @return
     */
    @PostMapping("/amountlist")
    @ResponseBody
    @AuthToken
    public ReturnVO amountlist(@RequestBody AppointmentVo data, HttpServletRequest request){
        result = new ReturnVO();
        List<ChargingFlowVo> datalist=new ArrayList<>();
        QueryWrapper<ChargingFlowVo> wrapper =new QueryWrapper<ChargingFlowVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //根据权限生成过滤条件
        if(roleID.equals("1")) {//管理员
        }else{//商户
            //调方法
            wrapper.inSql("u.userId","select userid from users where Activity=1 and UserID="+userId);
        }
        //正常查询过滤条件
        wrapper.eq("c.userId",data.getShopId());
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=chargingFlowService.counta(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= chargingFlowService.searcha(wrapper,new Page<>(data.getPageIndex(),data.getPageSize()));
        }
        result.setData(datalist);
        return result;
    }

}
